import Vue from 'vue'
import VueRouter from 'vue-router'
// 一级路由
import Admin from '../views/Admin'
import Login from '../views/Login'
import NotFound from '../views/NotFound'
import DashBoard from '../views/Admin/components/DashBoard'
import ArtList from '../views/Admin/components/ArtList'
import ArtAdd from '../views/Admin/components/ArtAdd'
import ArtEdit from '../views/Admin/components/ArtEdit'
import MsgList from '../views/Admin/components/MsgList'
import Settings from '../views/Admin/components/Settings'
import { getCookie } from '../utils/cookie'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/admin'
  },
  {
    path: '/admin',
    name: 'admin',
    component: Admin,
    // 配置二级路由
    redirect: '/admin/dashboard',
    children: [
      {
        path: '/admin/dashboard',
        name: '仪表盘',
        component: DashBoard,
        meta: {
          isNav: true,
          needLogin: true,
          role: true
        }
      },
      {
        path: '/admin/artlist',
        name: '文章列表',
        component: ArtList,
        meta: {
          isNav: true,
          needLogin: true,
          role: true
        }
      },
      {
        path: '/admin/artadd',
        name: 'artadd',
        component: ArtAdd,
        meta: {
          isNav: false,
          needLogin: true,
          role: true
        }
      },
      {
        path: '/admin/artedit/:id',
        name: 'artedit',
        component: ArtEdit,
        meta: {
          isNav: false,
          needLogin: true,
          role: true
        }
      },
      {
        path: '/admin/msglist',
        name: '消息中心',
        component: MsgList,
        meta: {
          isNav: true,
          needLogin: true,
          role: true
        }
      },
      {
        path: '/admin/settings',
        name: '设置',
        component: Settings,
        meta: {
          isNav: true,
          needLogin: false,
          role: false
        }
      }
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  {
    path: '*',
    name: 'notfound',
    component: NotFound
  }
]

const router = new VueRouter({
  routes
})

// 路由守卫做登录鉴权
router.beforeEach((to, from, next) => {
  // 判断哪些路由需要登录 需要登录 判断是否登录
  if (to.meta.needLogin) {
    // 需要登录权限
    // 判断是否登录
    const token = getCookie('access_token')
    if (token) {
      // 说明登录了
      next()
    } else {
      // 没有登录 去登录
      next({
        path: '/login'
      })
    }
  } else {
    next()
  }
})

export default router
